package com.wang.jmonkey.ca.handler.code;

import cn.hutool.core.codec.Base64;
import com.wang.jmonkey.ca.model.ValidateCode;
import com.wang.jmonkey.common.constant.ValidateConstant;
import com.wang.jmonkey.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * @Description 图形验证码生成器
 * @Author HeJiawang
 * @Date 2021/5/12 17:02
 */
@Slf4j
@Component("imageValidateCodeHandlerGenerator")
public class ImageValidateCodeGenerator implements ValidateCodeGenerator {

    @Override
    public ValidateCode generate() {
        int width = ValidateConstant.ImageProperty.ImgWidth.getKey();
        int height = ValidateConstant.ImageProperty.ImgHeight.getKey();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        String sRand = "";
        for (int i = 0; i < ValidateConstant.CodeNum.ImageCode.getKey(); i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 26);
        }

        g.dispose();

        ValidateCode result = new ValidateCode();
        try {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            ImageIO.write(image, "png", bao);
            String content = "data:image/png;charset=utf-8;base64," + Base64.encode(bao.toByteArray());

            result.setCode(sRand).setContent(content);
        } catch (IOException e) {
            log.error(this.getClass().getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(), e);

            throw new ServiceException("生成数字图片验证码失败!");
        }

        return result;
    }

    /**
     * 生成随机背景条纹
     * @param fc fc
     * @param bc bc
     * @return Color
     */
    private Color getRandColor(int fc, int bc) {
        fc = fc > 255 ? 255 : fc;
        bc = bc > 255 ? 255 : bc;

        Random random = new Random();
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);

        return new Color(r, g, b);
    }
}
